<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>coloredPoints</title>
</head>
<body>
<canvas width="500" height="500" style="border: 1px solid #333333"></canvas>
</body>
<script type="module">
    import {createProgram,createShader} from './utils.js'



    function main() {
        const vSource = `
            attribute vec4 a_position;
            void main(){
                gl_Position = a_position;
                gl_PointSize = 10.0;
            }
        `
        const fSource = `
            precision mediump float;
            uniform vec4 u_FragColor;
            void main(){
                gl_FragColor = u_FragColor;
            }
        `
        const canvas = document.querySelector('canvas')
        const gl = canvas.getContext('webgl')
        const vShader = createShader(gl,gl.VERTEX_SHADER,vSource)
        const fShader = createShader(gl,gl.FRAGMENT_SHADER,fSource)
        const program = createProgram(gl,vShader,fShader)
        const a_position = gl.getAttribLocation(program,'a_position')
        const u_FragColor = gl.getUniformLocation(program,'u_FragColor')
        gl.useProgram(program)
        gl.clearColor(0.0, 0.0, 0.0, 1.0)
        gl.clear(gl.COLOR_BUFFER_BIT)

        canvas.addEventListener('mousedown', function(){
            canvas.onmousemove = handlerMouseMove
        })
        canvas.addEventListener('mouseup',function () {
            canvas.onmousemove = null
        })
        const points = []
        const colors = [
            [1.0,0.0,0.0,1.0],
            [0.0,1.0,0.0,1.0],
            [0.0,0.0,1.0,1.0],
            [1.0,1.0,1.0,1.0],
        ]
        const handlerMouseMove = function(ev){
            const _clientX = ev.clientX
            const _clientY =ev.clientY
            const rect = ev.target.getBoundingClientRect()

            const canvasX = _clientX - rect.left
            const canvasY = _clientY - rect.top
            const glX = (canvasX - rect.width / 2) / (rect.width / 2)
            const glY = (rect.height / 2 - canvasY) / (rect.height / 2)
            points.push(glX,glY)

            gl.clear(gl.COLOR_BUFFER_BIT)
            for(let i = 0; i < points.length; i+=2){
                gl.vertexAttrib3f(a_position, points[i], points[i+1], 0.0)

                if(points[i] > 0 && points[i+1] > 0){
                    gl.uniform4f(u_FragColor,...colors[0])
                }else if(points[i] > 0 && points[i+1] < 0){
                    gl.uniform4f(u_FragColor,...colors[1])
                }else if(points[i] < 0 && points[i+1] < 0){
                    gl.uniform4f(u_FragColor,...colors[2])
                }else {
                    gl.uniform4f(u_FragColor,...colors[3])
                }
                gl.drawArrays(gl.POINTS, 0, 1)
            }
        }
    }

    main()

</script>
</html>